/**
 * @Project： Lqyd_Android
 * @Title：QyReaderApp
 * @Description：
 * @Author：wayne
 * @Date：2014年8月7日下午11:53:22
 */
package com.shwread.android.qysw;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Environment;

import com.NewActionHelp;
import com.TrainActionHelp;
import com.ciko.code.bean.UserBean;
import com.mywork.WorkUIKit;
import com.netease.nim.demo.NimCache;
import com.netease.nim.demo.main.activity.NimAVChatActivity;
import com.netease.nim.demo.session.SessionManager;
import com.netease.nim.demo.util.SystemUtil;
import com.netease.nim.demo.util.storage.StorageUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.step.model.UserHealthyDataModel;
import com.shwread.android.qysw10000204.R;
import com.shwread.greendao.gen.DaoMaster;
import com.shwread.greendao.gen.DaoSession;
import com.shwread.http.util.HttpResponseConfig;
import com.shwread.httpsdk.util.NetUtil;

import net.nightwhistler.htmlspanner.FontFamily;
import net.nightwhistler.pageturner.Configuration;

import org.geometerplus.zlibrary.ui.android.library.ZLAndroidApplication;

import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.constants.NoFormateConsts;
import logic.dao.UserDao;
import logic.util.AppUtils;
import logic.util.ImageLoaderUtil;
import logic.util.SDcardUtil;
import logic.util.ScreenUtil;
import logic.util.logutil.LogUtil;


public class QyReaderApp extends ZLAndroidApplication {
    //greendao
    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    public static String AREA_DB_NAME = "area-db";

    public static QyReaderApp application;

    public static QyReaderApp getApplication() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        //sd卡初始化
        SDcardUtil.init();
//		MultiDex.install(this);
        WorkUIKit.init(this);
        UserHealthyDataModel.getInstance().init();
        //初始化日志类
        LogUtil.isApplicationDebug(this);
        LogUtil.onError(this);
        ImageLoaderUtil.initImageLoader(this, null);

        //初始化屏幕数据
        ScreenUtil.GetInfo(this);

        //初始化云信相关数据
        StorageUtil.init(this, null);
        NimCache.setContext(this);
        NIMClient.init(this, getLoginInfo(), getOptions());

        HttpResponseConfig.CONTEXT = this;
        HttpResponseConfig.EXCEPTION_LOGIN_CODE = DefaultConsts.EXCEPTION_LOGIN_CODE;
        HttpResponseConfig.EXCEPTION_LOGIN_STRING = DefaultConsts.EXCEPTION_LOGIN_STRING;
        HttpResponseConfig.PARAMS_EMPTY_CODE = DefaultConsts.PARAMS_EMPTY_CODE;
        HttpResponseConfig.PARAMS_EMPTY_STRING = DefaultConsts.PARAMS_EMPTY_STRING;
        HttpResponseConfig.PACKAGE_NAME = AppUtils.getPackageName(this);
        NewActionHelp.init(NetUtil.getImei(this), NetUtil.getPsdnIp(), Const.SERVER_URL.equals("http://42.121.255.69:8080/hzlqswserver"));
        NewActionHelp.setEnterpriseId(NoFormateConsts.enterprise_num);
        NewActionHelp.setClientType(Const.CLIENTTYPE);
        NewActionHelp.initLion(true);
        TrainActionHelp.init(NetUtil.getImei(this), NetUtil.getPsdnIp(), Const.TRAIN_URL.equals("http://42.121.253.209:8081/lqsw_website/"));
        TrainActionHelp.setEnterpriseId(NoFormateConsts.enterprise_num);
        TrainActionHelp.setClientType(Const.CLIENTTYPE);

        //		// 在IntentFilter中选择你要监听的行为
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);// sd卡被插入，且已经挂载
        intentFilter.setPriority(1000);// 设置最高优先级
        registerReceiver(new SDBroadcastReceiver(), intentFilter);// 注册监听函数

        if (inMainProcess()) {
            // init pinyin
            //            PinYin.init(this);
            //            PinYin.validate();

            // 开启/关闭通知栏消息提醒
            NIMClient.toggleNotification(true);
            SessionManager.init();
            enableAVChat();
        }

        initFontfamily();
        setDatabase();
    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {
        // 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
        // 注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, AREA_DB_NAME, null);
        db = mHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    private void enableAVChat() {
        registerAVChatIncomingCallObserver(true);
    }

    private void registerAVChatIncomingCallObserver(boolean register) {
        AVChatManager.getInstance().observeIncomingCall(new Observer<AVChatData>() {
            @Override
            public void onEvent(AVChatData chatData) {
                String account;
                UserBean user = UserDao.getInstance(getApplicationContext()).getLastLoginUser();
                if (user == null) {
                    account = NimCache.getAccount();
                } else {
                    account = user.getImAccount();
                }
                NimAVChatActivity.launch(getApplicationContext(), account, chatData.getAccount(), chatData.getChatType().getValue(), false);
            }
        }, register);
    }

    public static class SDBroadcastReceiver
            extends
            BroadcastReceiver {

        public SDBroadcastReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("android.intent.action.MEDIA_MOUNTED"))// SD
            // 卡已经成功挂载
            {
                SDcardUtil.init();
            }
        }

    }

    private SDKOptions getOptions() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给SDK完成，需要添加以下配置。
        // 其中notificationSmallIconId必须提供
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = MainActivity.class;
        config.notificationSmallIconId = R.drawable.ic_launcher;
        options.statusBarNotificationConfig = config;
        NimCache.setConfig(config);

        // 配置保存图片，文件，log等数据的目录
        String sdkPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/nim";
        options.sdkStorageRootPath = sdkPath;

        // 配置数据库加密秘钥
        options.databaseEncryptKey = "NETEASE";

        // 配置是否需要预下载附件缩略图
        options.preloadAttach = true;

        // 配置附件缩略图的尺寸大小，
        options.thumbnailSize = ScreenUtil.screenMin / 2;

        return options;
    }

    private LoginInfo getLoginInfo() {
        //        String account = Preferences.getUserAccount();
        //        String token = Preferences.getUserToken();
        //
        //        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
        //            DemoCache.setAccount(account);
        //            // open db
        //            DatabaseManager.getInstance().open(this);
        //            return new LoginInfo(account, token);
        //        } else {
        return null;
        //        }
    }

    public boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = SystemUtil.getProcessName(this);
        return packageName.equals(processName);
    }

    private static FontFamily kaiFontFamily;

    public static FontFamily getFontFamily() {
        return kaiFontFamily;
    }

    private void initFontfamily() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Typeface basic = Typeface.createFromAsset(getAssets(), "fonts/" + Configuration.CN_FONT_KAITI + ".ttf");
                kaiFontFamily = new FontFamily(Configuration.CN_FONT_KAITI, basic);
            }
        }).start();
    }
}
